package frist50;

import org.junit.jupiter.api.Test;

import java.util.Arrays;

public class T0016 {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int diff = Integer.MAX_VALUE;
        int len = nums.length;
        int re = nums[0] + nums[1] + nums[2];
        for (int frist = 0; frist < len; frist++) {
            if (frist > 0 && nums[frist] == nums[frist - 1]) continue;
            int third = len - 1;
            int targetS = target - nums[frist];
            for (int second = frist + 1; second < third; second++) {
                if (second > frist + 1 && nums[second] == nums[second - 1]) continue;
                int tmpDiff;
                while (second < third && nums[second] + nums[third] > targetS) {
                    tmpDiff = nums[second] + nums[third] - targetS;
                    if (Math.abs(diff) > Math.abs(tmpDiff)) {
                        diff = tmpDiff;
                        re = nums[frist] + nums[second] + nums[third];
                    }
                    third--;
                }
                if (second==third)break;
                tmpDiff = nums[second] + nums[third] - targetS;
                if (Math.abs(diff) > Math.abs(tmpDiff)) {
                    diff = tmpDiff;
                    re = nums[frist] + nums[second] + nums[third];
                }
            }
        }
        return re;
    }

    @Test
    public void test() {


        int[] ints = {-1, 2, 1, -4};
        System.out.println(threeSumClosest(ints, 1));

    }
}
